package com.yfqy.app.modules.wechat.controller;

import com.yfqy.app.modules.wechat.service.WechatCallbackService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/public/wechat")
public class WechatCallbackController {

    @Autowired
    private WechatCallbackService wechatCallbackService;

    /**
     * 支付回调处理
     */
    @PostMapping("/callback")
    public ResponseEntity<String> payCallback(HttpServletRequest request) {
        return ResponseEntity.ok(wechatCallbackService.paymentNotify(request));
    }


    /**
     * 退款结果通知回调
     */
    @PostMapping("/refund/callback")
    public ResponseEntity<Map<String, String>> refundCallback(HttpServletRequest request) {
        Map<String, String> result = new HashMap<>();

        try {
            // 获取回调数据
            StringBuilder xmlData = new StringBuilder();
            String line;
            while ((line = request.getReader().readLine()) != null) {
                xmlData.append(line);
            }

            //log.info("退款回调数据: {}", xmlData.toString());

            // 这里应该验证签名和解析XML数据
            // 实际项目中需要：
            // 1. 验证微信支付退款回调的签名
            // 2. 解析XML数据获取退款信息
            // 3. 验证退款状态
            // 4. 更新业务退款状态
            // 5. 处理业务逻辑

            result.put("return_code", "SUCCESS");
            result.put("return_msg", "OK");

        } catch (Exception e) {
            //log.error("退款回调处理异常", e);
            result.put("return_code", "FAIL");
            result.put("return_msg", "处理失败");
        }

        return ResponseEntity.ok(result);
    }
}
